package client;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;

import java.util.concurrent.TimeUnit;

public class MyClientBoot {

    public void connect(){
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(1);
        bootstrap.group(workerGroup).channel(NioSocketChannel.class)
        .remoteAddress("o22t794510.51mypc.cn", 10263)
//        .remoteAddress("103.46.128.53", 10263)
        .handler(new ChannelInitializer<SocketChannel>(){
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new MyClientPipeline());
            }
        });
        ChannelFuture  future = null;
        try {
              future = bootstrap.connect().sync();
            if(future.isSuccess()){
                System.out.println("连接成功");
                future.addListener((ChannelFutureListener) futureListener -> {
                    System.out.println("监听--开始尝试");
                    if (futureListener.isSuccess()) {
                        System.out.println("监听--连接成功");
                    } else {
                        System.out.println("监听--尝试重新连接...");
                        futureListener.channel().eventLoop().schedule(new Runnable() {
                            @Override
                            public void run() {
                                new MyClientBoot().connect();
                            }
                        }, 1, TimeUnit.SECONDS);
                    }
                });
            }
           // future.channel().closeFuture().sync();
        } catch (Exception e) {
            if(future!=null){
                future.channel().closeFuture();
            }
            workerGroup.shutdownGracefully();//不加线程会一直驻留
            System.out.println("尝试重新连接...");
            connect();
        }
//        finally {
//            workerGroup.shutdownGracefully();
//        }

    }

    public static void main(String[] args) {
        MyClientBoot myClientBoot = new MyClientBoot();
        myClientBoot.connect();
    }

}
